package app.core.thread;


import app.core.model.impl.Message;

import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author Guo.Yang
 * @version 1.0
 * @date 2023/1/15 17:26
 */
public class ClientRunnable extends MyRunnable {

    private Socket socket;
    private Consumer<Message> consumer;

    public ClientRunnable(Socket socket, Consumer<Message> consumer){
        this.consumer = consumer;
        this.socket = socket;
    }
    @Override
    public void run() {

        while (socket.isConnected()){
            byte[] bytes = new byte[BYTES_MAX_SIZE];
            try {
                int read = socket.getInputStream().read(bytes, 0, BYTES_MAX_SIZE);
                if (read > 0){
                    String data = new String(bytes, 0, read, CHAR_SET);
                    List<Message> messages = Message.create(data);
                    messages.forEach(message -> consumer.accept(message));
                }
                Thread.sleep(100);
            } catch (IOException | InterruptedException e) {
                System.out.println("连接出现异常:"+ e.getMessage());
                break;
            }catch (Exception un){
                System.out.println("未知异常:"+ un.getMessage());
            }
        }
    }
}
